package com.toy.abash.service.impl;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;

import com.toy.abash.dao.ReplyDAO;
import com.toy.abash.domain.Abash;
import com.toy.abash.domain.Reply;
import com.toy.abash.service.AbashManager;
import com.toy.abash.service.ReplyManager;
import com.toy.base.domain.User;
import com.toy.base.service.UserManager;
import com.toy.core.cache.annotation.CacheEvict;
import com.toy.core.cache.annotation.CachePackage;
import com.toy.core.cache.annotation.CachePutGet;
import com.toy.core.dao.MongoCrudRepository;
import com.toy.core.service.impl.BaseManagerImpl;

@CachePackage(Reply.class)
@Service("replyManager")
public class ReplyManagerImpl extends BaseManagerImpl<Reply> implements
		ReplyManager {
	
	@Autowired
	private ReplyDAO repliesDAO; 
	
	@Autowired
	private AbashManager abashManager;
	
	@Autowired
	private UserManager userManager;
	
	@Override
	public MongoCrudRepository<Reply,Long> getMongoCrudRepository() {
		return repliesDAO;
	}
	
	@CacheEvict
	public Reply saveReply(Reply entity){
		entity = repliesDAO.save(entity);
		Abash abash =  abashManager.getById(entity.getAbashId());
		Update update = new Update();
		update.inc("replyNum", 1).inc("hotOrder", 1);
		abashManager.findAndModify(abash.getId(), update);
		return entity;
	}
	
	@CachePutGet
	public List<Reply> findReplyByPostId(Long postId){
		List<Criteria> criterions = new ArrayList<Criteria>(2);
		criterions.add(Criteria.where("state").is(Reply.STATE_NORMAL));
		//TIPS:外键关联查询
		criterions.add(Criteria.where("abashId").is(postId));
		return repliesDAO.findByCriterion(criterions,"_id",true);
	}
	
	@CachePutGet
	public Map<Long, User> findReplysUsers(List<Reply> list) {
		if ( list == null || list.size() == 0){
			return Collections.emptyMap();
		}
		Set<Long> userIds = new HashSet<Long>();
		for (Reply reply : list) {
			userIds.add(reply.getReplierId());
		}
		return userManager.findByUserIds(userIds);
	}

}
